<template>
  <div class="task-attachment">
    <div class="attachment-header">
      <el-upload
        :action="''"
        :http-request="handleUpload"
        :show-file-list="false"
        :disabled="disabled"
      >
        <el-button size="mini" type="primary" icon="el-icon-upload" :disabled="disabled">上传附件</el-button>
      </el-upload>
    </div>
    
    <el-table
      v-loading="loading"
      :data="attachmentList"
      style="width: 100%"
    >
      <el-table-column label="文件名称" prop="fileName" show-overflow-tooltip />
      <el-table-column label="文件类型" prop="fileType" width="100" />
      <el-table-column label="文件大小" width="100">
        <template slot-scope="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="上传时间" width="180">
        <template slot-scope="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
          >下载</el-button>
          <el-button
            v-if="!disabled"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { listAttachmentsByTask, uploadAttachment, downloadAttachment, delAttachment } from '@/api/task/attachment'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'TaskAttachment',
  props: {
    taskId: {
      type: [Number, String],
      required: true
    },
    taskType: {
      type: Number,
      default: 0, // 0=主任务, 1=子任务
      validator: (value) => [0, 1].includes(value)
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      attachmentList: []
    }
  },
  watch: {
    taskId: {
      handler(val) {
        if (val) {
          this.getAttachmentList()
        } else {
          this.attachmentList = []
        }
      },
      immediate: true
    }
  },
  methods: {
    // 获取附件列表
    getAttachmentList() {
      if (!this.taskId) return
      
      this.loading = true
      listAttachmentsByTask(this.taskId, this.taskType).then(response => {
        this.attachmentList = response.data || []
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    
    // 上传附件
    handleUpload(options) {
      const { file } = options
      
      uploadAttachment(this.taskId, this.taskType, file).then(response => {
        this.$modal.msgSuccess('上传成功')
        this.getAttachmentList()
      }).catch(error => {
        this.$modal.msgError('上传失败：' + error.message)
      })
    },
    
    // 下载附件
    handleDownload(row) {
      downloadAttachment(row.attachmentId).then(response => {
        const blob = new Blob([response.data])
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = row.fileName
        link.click()
        URL.revokeObjectURL(link.href)
      }).catch(error => {
        this.$modal.msgError('下载失败：' + error.message)
      })
    },
    
    // 删除附件
    handleDelete(row) {
      this.$modal.confirm('确定要删除该附件吗？').then(() => {
        delAttachment(row.attachmentId).then(() => {
          this.$modal.msgSuccess('删除成功')
          this.getAttachmentList()
        }).catch(error => {
          this.$modal.msgError('删除失败：' + error.message)
        })
      }).catch(() => {})
    },
    
    // 格式化文件大小
    formatFileSize(size) {
      if (!size) return '0 B'
      
      const units = ['B', 'KB', 'MB', 'GB', 'TB']
      let index = 0
      let fileSize = size
      
      while (fileSize >= 1024 && index < units.length - 1) {
        fileSize /= 1024
        index++
      }
      
      return fileSize.toFixed(2) + ' ' + units[index]
    },
    
    // 格式化时间
    parseTime
  }
}
</script>

<style scoped>
.task-attachment {
  margin-top: 15px;
}
.attachment-header {
  margin-bottom: 10px;
  text-align: right;
}
</style> 